package com.kmproject.haifu.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.CustomPopupWindow;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.AliYunDunCheckInterface;
import com.kmproject.haifu.app.hfinterface.WebViewCheakInterface;
import com.kmproject.haifu.app.utils.PwdCheckUtil;
import com.kmproject.haifu.di.component.DaggerUserForgetPwdComponent;
import com.kmproject.haifu.mvp.contract.UserForgetPwdContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.VerificationBean;
import com.kmproject.haifu.mvp.model.entity.resbean.H5CheckCodeBean;
import com.kmproject.haifu.mvp.presenter.UserForgetPwdPresenter;
import com.xw.repo.XEditText;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.ibooker.zcountdownviewlib.SingleCountDownView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/23/2019 14:39
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class UserForgetPwdActivity extends BaseActivity<UserForgetPwdPresenter> implements UserForgetPwdContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.user_phone_Attribution_txt)
    TextView userPhoneAttributionTxt;
    @BindView(R.id.user_phone_Attribution_img)
    ImageView userPhoneAttributionImg;
    @BindView(R.id.user_phone_txt)
    XEditText userPhoneTxt;
    @BindView(R.id.user_pwd_txt)
    XEditText userPwdTxt;
    @BindView(R.id.user_forgetPwd_zym_singleCountDownView)
    SingleCountDownView userForgetPwdZymSingleCountDownView;
    @BindView(R.id.user_forgetPwd_btn)
    TextView userForgetPwdBtn;
    private boolean isTimefinish = true;
    String mytemPhone = "";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerUserForgetPwdComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_user_forget_pwd; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (getIntent().hasExtra("type") && getIntent().getStringExtra("type").equals("housePublic")) {
            //发布房屋界面跳转过来的
            SpannableString s = new SpannableString(ArmsUtils.getString(this, R.string.housepublishpublish_info_title_qsrxdlxfs));//这里输入自己想要的提示文字
            userPhoneTxt.setHint(s);
            userForgetPwdBtn.setText("确定");

        } else {
            userPhoneTxt.setTextEx(getIntent().getStringExtra("mobile"));
            if (userPhoneTxt.getText().toString().length() > 0 && userPhoneTxt.getText().toString().startsWith("1")) {
                userPhoneAttributionTxt.setText("+86");
            } else {
                userPhoneAttributionTxt.setText("+63");
            }
        }

        setYzmBtnStatus(false);
        if (userPhoneTxt.getText().toString().length() > 9) {
            setYzmBtnStatus(true);
        } else {
            setYzmBtnStatus(false);
        }


        userPhoneTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 9) {
                    setYzmBtnStatus(true);
                } else {
                    setYzmBtnStatus(false);
                }
                if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(userPwdTxt.getText().toString()) && userPwdTxt.getText().toString().length() == 6) {
                    setBtnStatus(true);
                } else {
                    setBtnStatus(false);
                }
            }
        });

        userPwdTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().contains(" ")) {
                    setBtnStatus(false);
                    return;
                }
                if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(userPhoneTxt.getText().toString()) && userPwdTxt.getText().toString().length() == 6) {
                    setBtnStatus(true);
                } else {
                    setBtnStatus(false);
                }
            }
        });


// 单个倒计时结束事件监听
        userForgetPwdZymSingleCountDownView.setSingleCountDownEndListener(new SingleCountDownView.SingleCountDownEndListener() {
            @Override
            public void onSingleCountDownEnd() {
                // 倒计时结束
                isTimefinish = true;
                setYzmBtnStatus(true);
            }
        });
    }

    @Override
    public String reSetTitle() {
        return ((getIntent().hasExtra("type") && getIntent().getStringExtra("type").equals("housePublic"))) ? ArmsUtils.getString(this, R.string.housepublishpublish_info_title_bglxdh) : ArmsUtils.getString(this, R.string.user_login_forgetpwd_title);

    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.user_phone_Attribution_txt, R.id.user_phone_Attribution_img, R.id.user_forgetPwd_zym_singleCountDownView, R.id.user_forgetPwd_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_phone_Attribution_txt:
                showPopuWindow();
                break;
            case R.id.user_phone_Attribution_img:
                showPopuWindow();
                break;
            case R.id.user_forgetPwd_zym_singleCountDownView:
                if (!isTimefinish) {
                    showMessage("稍后再试");
                    return;
                }

                if (userPhoneAttributionTxt.getText().toString().equals("+63")) {
                    if (userPhoneTxt.getText().toString().substring(0, 1).equals("0")) {
                        showMessage("手机号不能是0开头");
                        return;
                    }
                    if (!userPhoneTxt.getText().toString().substring(0, 1).equals("9")) {
                        showMessage("手机号必须是9开头");
                        return;
                    }
                    if (userPhoneTxt.getText().toString().length() != 10) {
                        showMessage("手机号长度必须是十位");
                        return;
                    }
                    mytemPhone = "63" + userPhoneTxt.getText().toString();
                } else {
                    if (userPhoneTxt.getText().toString().length() != 11) {
                        showMessage("手机号必须是11位");
                        return;
                    }
                    mytemPhone = "86" + userPhoneTxt.getText().toString();
                }

                if (getIntent().hasExtra("type") && getIntent().getStringExtra("type").equals("housePublic")) {
                    mPresenter.sendHouseVerifyCode(mytemPhone);
                    //校验手机号码
                    return;
                }
                showCheackDialog(this, userForgetPwdZymSingleCountDownView, mytemPhone);
//                PwdCheckUtil.callSDKDoVerification(this, VerifyType.NOCAPTCHA, null, new AliYunDunCheckInterface() {
//                    @Override
//                    public void aliYunDunCheckCallBack(int retInt, Map code) {
//                        switch (retInt) {
//                            case VerifyActivity.VERIFY_SUCC:
//                                Log.e("####", code.toString());
//                                String sessionid = (String) code.get("sessionID");
////                                setLogMessage("验证通过:\nsessionId=" + (String) code.get("sessionID"));
//
//                                mPresenter.queryVerification(mytemPhone,sessionid,AppConstant.ALIYUNDUN_CHECK_APPID);
//                                break;
//
//                            case VerifyActivity.VERIFY_FAILED:
//                                ArmsUtils.makeText(UserForgetPwdActivity.this,(String) (null != code.get("errorMsg") ? code.get("errorMsg") : ""));
//                                VerifyActivity.finishVerifyUI();
//                                break;
//                        }
//                    }
//                });

//
                break;
            case R.id.user_forgetPwd_btn:

                if (userPhoneAttributionTxt.getText().toString().equals("+63")) {
                    if (userPhoneTxt.getText().toString().substring(0, 1).equals("0")) {
                        showMessage("手机号不能是0开头");
                        return;
                    }
                    if (!userPhoneTxt.getText().toString().substring(0, 1).equals("9")) {
                        showMessage("手机号必须是9开头");
                        return;
                    }
                    if (userPhoneTxt.getText().toString().length() != 10) {
                        showMessage("手机号长度必须是十位");
                        return;
                    }
                    mytemPhone = "63" + userPhoneTxt.getText().toString();
                } else {
                    if (userPhoneTxt.getText().toString().length() != 11) {
                        showMessage("手机号必须是11位");
                        return;
                    }
                    mytemPhone = "86" + userPhoneTxt.getText().toString();
                }
                if (getIntent().hasExtra("type") && getIntent().getStringExtra("type").equals("housePublic")) {
                    mPresenter.houseCheckIsCorrectCode(mytemPhone, userPwdTxt.getText().toString().trim());
                    //校验手机号码
                    return;
                }
                Map<String, Object> maps = new HashMap<>();
                maps.put("identifyCode", userPwdTxt.getText().toString().trim());
                maps.put("mobile", mytemPhone);
                mPresenter.forgotPwdNext(maps);
                break;
        }
    }

    /**
     * 设置登录按钮状态
     *
     * @param isClick
     */
    public void setBtnStatus(boolean isClick) {
        if (isClick) {
            userForgetPwdBtn.setEnabled(true);
            userForgetPwdBtn.setBackgroundResource(R.drawable.button_yellow_bg);
            userForgetPwdBtn.setTextColor(getResources().getColor(R.color.color_191919));
        } else {
            userForgetPwdBtn.setEnabled(false);
            userForgetPwdBtn.setBackgroundResource(R.drawable.button_gray_bg);
            userForgetPwdBtn.setTextColor(getResources().getColor(R.color.color_EDEDED));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (userForgetPwdZymSingleCountDownView != null) {
            userForgetPwdZymSingleCountDownView.pauseCountDown();
        }
    }

    /**
     * 设置验证码按钮的状态
     *
     * @param isClick
     */
    public void setYzmBtnStatus(boolean isClick) {
        if (userForgetPwdZymSingleCountDownView == null) {
            return;
        }
        if (isClick) {
            userForgetPwdZymSingleCountDownView.setEnabled(true);
            userForgetPwdZymSingleCountDownView.setTextColor(getResources().getColor(R.color.color_191919));
            userForgetPwdZymSingleCountDownView.setBackgroundResource(R.drawable.box_black_white_bg);
            userForgetPwdZymSingleCountDownView.setText(getResources().getString(R.string.user_requery_yzm));
        } else {
            userForgetPwdZymSingleCountDownView.setEnabled(false);
            userForgetPwdZymSingleCountDownView.setTextColor(getResources().getColor(R.color.color_C6C6C6));
            userForgetPwdZymSingleCountDownView.setBackgroundResource(R.drawable.box_gray_white_bg);
            userForgetPwdZymSingleCountDownView.setText(getResources().getString(R.string.user_requery_yzm));
        }
    }

    /**
     * 控制popu显示
     */
    public void showPopuWindow() {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(this, R.layout.user_popuwindow_view)).parentView(userPhoneAttributionTxt).backgroundDrawable(getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).build();
        View view1 = customPopupWindow.getContentView();
        TextView user_popuwindow_view_flb = view1.findViewById(R.id.user_popuwindow_view_flb);
        TextView user_popuwindow_view_zg = view1.findViewById(R.id.user_popuwindow_view_zg);
        user_popuwindow_view_flb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userPhoneAttributionTxt.setText("+63");
                customPopupWindow.dismiss();
            }
        });
        user_popuwindow_view_zg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userPhoneAttributionTxt.setText("+86");
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.show();
    }

    @Override
    public void queryVerificationSuccess(VerificationBean verificationBean) {
        if (verificationBean != null) {
            userPwdTxt.setText(verificationBean.getCode());
        }
        isTimefinish = false;
        // 开启倒计时
        userForgetPwdZymSingleCountDownView.setTime(60)
                .setTimeColorHex("#191919")
//                        .setTimePrefixText("前缀")
                .setTimeSuffixText("s")
                .startCountDown();
    }

    @Override
    public void sendHouseVerifyCodeSuccess(VerificationBean verificationBean) {
        if (verificationBean != null) {
            userPwdTxt.setText(verificationBean.getCode());
        }

    }

    @Override
    public void houseCheckIsCorrectCodeSuccess() {
        Intent intent = new Intent();
        intent.putExtra("phone", userPhoneTxt.getText().toString());
        setResult(RESULT_OK, intent);
        killMyself();
    }

    @Override
    public void forgotPwdNextSuccess(ResultBean resultBean) {
        Intent intent = new Intent(this, UserResetPwdActivity.class);
        intent.putExtra("type", "resetPwd");
        intent.putExtra("mobile", mytemPhone);
        intent.putExtra("identifyCode", userPwdTxt.getText().toString().trim());
        ArmsUtils.startActivityForResult(intent, AppConstant.START_ACTIVITY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == AppConstant.START_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            //需要结束当前界面，回到登录界面
            killMyself();
        }
    }

    /**
     * h5投篮验证
     *
     * @param activity
     * @param view
     */
    public void showCheackDialog(Activity activity, View view, String mytemPhone) {
        CustomPopupWindow dialog = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(activity, R.layout.user_login_cheak_dialog)).parentView(view)
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isHaveBackGround(true).isWrap(true).build();
        View view2 = dialog.getContentView();
        ImageView user_login_cheak_dialog_img = view2.findViewById(R.id.user_login_cheak_dialog_img);
        user_login_cheak_dialog_img.setImageResource(R.drawable.login_cheak_img);
        initView(view2, new WebViewCheakInterface() {
            @Override
            public void callBack(String data) {
                H5CheckCodeBean h5CheckCodeBean = null;
                try {
                    h5CheckCodeBean = new Gson().fromJson(data, H5CheckCodeBean.class);
                    Map<String, Object> maps = new HashMap<>();
                    maps.put("phoneNum", mytemPhone);
                    maps.put("appKey", h5CheckCodeBean.getAppkey());
                    maps.put("scene", h5CheckCodeBean.getScene());
                    maps.put("sessionId", h5CheckCodeBean.getSessionid());
                    maps.put("sig", h5CheckCodeBean.getSig());
                    maps.put("token", h5CheckCodeBean.getNc_token());
                    mPresenter.forgotPwdMessage_new(maps);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    ArmsUtils.makeText(UserForgetPwdActivity.this, "校验失败");
                }

                view2.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //两秒后关闭弹框
                        dialog.dismiss();

                    }
                }, 2000);
            }
        });
        dialog.show();
    }

    private void initView(View view, WebViewCheakInterface webViewCheakInterface) {
        // 页面布局。
        WebView testWebview = (WebView) view.findViewById(R.id.user_login_cheak_dialog_WebView);
        // 设置屏幕自适应。
        testWebview.getSettings().setUseWideViewPort(true);
        testWebview.getSettings().setLoadWithOverviewMode(true);
        // 建议禁止缓存加载，以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
        testWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置不使用默认浏览器，而直接使用WebView组件加载页面。
        testWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        // 设置WebView组件支持加载JavaScript。
        testWebview.getSettings().setJavaScriptEnabled(true);
        // 建立JavaScript调用Java接口的桥梁。
        testWebview.addJavascriptInterface(new testJsInterface(webViewCheakInterface), "testInterface");
        // 加载业务页面。
        testWebview.loadUrl(Api.url_h5_check);
    }

    public class testJsInterface {
        WebViewCheakInterface webViewCheakInterface;

        public testJsInterface(WebViewCheakInterface mwebViewCheakInterface) {
            webViewCheakInterface = mwebViewCheakInterface;
        }

        @JavascriptInterface
        public void getSlideData(String callData) {
            System.out.println(callData);
            Log.i("#####", callData);
            webViewCheakInterface.callBack(callData);
        }
    }
}
